package com.alibaba.citrus.cr.price.ability.facade;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.price.repository.CreditQueryRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Response;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.enums.RoleCodeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetDownOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crpricecenter.api.creditquery.dto.BatchQueryCreditListRequest;
import com.epoch.app.crpricecenter.api.creditquery.dto.QueryCompanyToGroupCreditListRequest;
import com.epoch.app.crpricecenter.api.creditquery.dto.RefreshSyncQueryCreditRequest;
import com.epoch.app.crpricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.crpricecenter.api.creditwrite.service.CreditWriteService;
import com.epoch.app.crpricecenter.contants.CrPriceCenterConstants;
import com.epoch.app.crpricecenter.model.dto.BatchCreditQueryRequest;
import com.epoch.app.crpricecenter.model.dto.BatchSyncQueryCreditRequest;
import com.epoch.app.crpricecenter.model.dto.CompanyToGroupCreditResponse;
import com.epoch.app.crpricecenter.model.dto.CreditCallbackRequest;
import com.epoch.app.crpricecenter.model.dto.CreditInfoSDO;
import com.epoch.app.crpricecenter.model.dto.CreditQueryRequest;
import com.epoch.app.crpricecenter.model.dto.MnSap020CallbackSDO;
import com.epoch.app.crpricecenter.model.dto.MnSap020Response;
import com.epoch.app.crpricecenter.model.dto.MnSapIf020SDO;
import com.epoch.app.crpricecenter.model.dto.RestSapQueryCreditForCompanyToGroupSyncRequest;
import com.epoch.app.crpricecenter.model.dto.SyncQueryCreditRequest;
import com.epoch.app.crpricecenter.service.CrPriceCenterService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: qianlei
 * @create: 2021/10/29 01:08
 */
@Service
@Primary
public class CreditQueryServiceImpl implements CreditQueryService {
    @Autowired
    CreditQueryRepository creditQueryRepository;

    @Autowired
    private BcOrderService bcOrderService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;
    @Resource
    private CrPriceCenterService crPriceCenterService;
    @Resource
    private EpochCacheService epochCacheService;
    @Resource
    private CreditWriteService creditWriteService;

    private static Log log = Log.getLogger(CreditQueryServiceImpl.class);

    //常温事业部组织编码
    private static final String SALE_ORGANIZATION_CODE = "6000";
    //分销渠道
    private static final String SAP_CHANNEL = "20";
    //产品组
    private static final String PRODUCT_GROUP_CODE = "11";
    private static final int MAX_LENGTH = 10;
    private static final String REFRESH_CREDIT_QUERY_KEY = "REFRESH_CREDIT_QUERY_KEY";
    private static final Long REFRESH_TIME_EXPIRE = 60l * 5;
    //47家分子公司
    private Set<String> targetSoldPartCodesSet = Sets.newHashSet("1900008263","1900001227","1900000827","1900043735","1900038445",
            "1900035293","1900029519","1900023074","1900008664","1900008459","1900000826","1900000825","1900000822","1900000814","1900000813",
            "1900000803","1900000801","1900000800","1900000799","1900024235","1900022946","1900037741","1900036869","1900035437","1900029687",
            "1900019218","1900009463","1900008915","1900008535","1900008241","1900000821","1900000819","1900000810","1900000806","1900000093",
            "1900000824","1900004400","1900024582","1900035757","1900000807","1900000805","1900008362","1900000812","1900000820","1900000818",
            "1900000816","1900000001");

    @Override
    @FacadeInvoker(value = "查询信贷余额", errorCode = "OTS-07-006-01-16-002")
    public Result<List<CreditInfoSDO>> queryCredit(BatchCreditQueryRequest batchCreditQueryRequest) {
        if(CollectionUtils.isEmpty(batchCreditQueryRequest.getCreditQueryList())){
            return Result.success(null);
        }
        CreditInfoSDO creditInfoSDO = batchCreditQueryRequest.getCreditQueryList().get(0);
        if(StringUtils.isBlank(creditInfoSDO.getCustomerCode()) && StringUtils.isBlank(creditInfoSDO.getClientCode())){
           throw new FacadeException("OTS-07-010-01-17-002");
        }
        //如果用户是手动填的客户编码数据，则以这个数据为客户编码查询条件
        if(StringUtils.isNotBlank(creditInfoSDO.getClientCode())){
            creditInfoSDO.setCustomerCode(creditInfoSDO.getClientCode());
        }
        Result<List<CreditInfoSDO>> validResult = invalidPermission();
        if (validResult != null) {
            return validResult;
        }
        List<CreditInfoSDO> list;

        list = creditQueryRepository.queryCreditList(batchCreditQueryRequest.getCreditQueryList());

        if (CollectionUtils.isNotEmpty(list)){
            for (CreditInfoSDO infoSDO : list) {
                if (Objects.isNull(infoSDO)||!"成功".equals(infoSDO.getMessage())){
                   return Result.fail(infoSDO.getMessage(),infoSDO.getMessage());
                }
            }
        }
        return Result.success(list);
    }

    @Nullable
    private Result<List<CreditInfoSDO>> invalidPermission() {
        List<CreditInfoSDO> list = new ArrayList<>();
        // 控制角色
        EmployeeGetCurrentLoginResponse currentLoginEmployeeRoles = bcOrderService.employeeGetCurrentLogin();
        if (currentLoginEmployeeRoles != null && StringUtils.isNotBlank(currentLoginEmployeeRoles.getRoleCodes())){
            String roleCodes = currentLoginEmployeeRoles.getRoleCodes();
            if (StringUtils.isBlank(roleCodes) || "[]".equals(roleCodes)){
                return Result.success(list);
            }
            List<String> noPermissionRoleCodeList = Lists.newArrayList(RoleCodeEnum.SALE_MAN.getCode(), RoleCodeEnum.DEPARTMENT_MANAGER.getCode());
            String trimRoleCodes = roleCodes.replaceAll(" ", "");
            List<String> roles = Lists.newArrayList(trimRoleCodes.substring(1, trimRoleCodes.length() - 2).split(","));
            boolean permission = false;
            for (String role : roles) {
                if (!noPermissionRoleCodeList.contains(role)) {
                    permission = true;
                    break;
                }
            }
            if (!permission){
                return Result.success(list);
            }
        }
        return null;
    }

    @Override
    @FacadeInvoker(value = "查询信贷余额", errorCode = "OTS-07-006-01-16-002")
    public Result<CreditInfoSDO> queryCreditBalance(CreditQueryRequest creditQueryRequest){
        CreditInfoSDO sdo = new CreditInfoSDO();
        sdo.setOrganizationCode(creditQueryRequest.getOrganizationCode());
        sdo.setChannelCode(creditQueryRequest.getChannelCode());
        sdo.setItemGroupCode(creditQueryRequest.getItemGroupCode());
        sdo.setCustomerCode(creditQueryRequest.getCustomerCode());
        sdo.setClientCode(creditQueryRequest.getClientCode());
        sdo.setSaleOrderId(creditQueryRequest.getSaleOrderId());
        List<CreditInfoSDO> list = creditQueryRepository.queryCreditList(Lists.newArrayList(sdo), false);
        if (CollectionUtils.isNotEmpty(list)){
            CreditInfoSDO resp = list.get(0);
            if (resp.getSuccess()){
                return Result.success(resp,resp.getMessage());
            }
            log.error("OTS-07-006-01-16-002",resp);
            return Result.fail("OTS-07-006-01-16-002", "查询信贷余额失败！");

        }
        //todo 先临时这样处理
        return Result.fail(null,"OTS-07-006-01-16-002","查询信贷余额失败！");
    }

    @Override
    @FacadeInvoker(value = "查询信贷余额", errorCode = "OTS-07-006-01-16-002")
    public Result<List<CreditInfoSDO>> batchQueryCreditList(BatchQueryCreditListRequest batchQueryCreditListRequest){
        if(CollectionUtils.isEmpty(batchQueryCreditListRequest.getRequestList())){
            return Result.success(null);
        }

        boolean customerEmpty = batchQueryCreditListRequest.getRequestList().stream().anyMatch(o -> StringUtils.isBlank(o.getCustomerCode()));
        if(customerEmpty){
            throw new FacadeException("OTS-07-010-01-17-002");
        }

        Result<List<CreditInfoSDO>> validResult = invalidPermission();
        if (validResult != null){
            return validResult;
        }
        List<CreditInfoSDO> list = new ArrayList<>();
        //modify by myw,20230425,consider the performance pressure of the interface
        int creditPageSize = Objects.isNull(CrPriceCenterConstants.CREDIT_PAGE_SIZE())?50:CrPriceCenterConstants.CREDIT_PAGE_SIZE().intValue();
        for (List<CreditQueryRequest> creditQueryRequestList : Lists.partition(batchQueryCreditListRequest.getRequestList(), creditPageSize)) {
            try {
                List<CreditInfoSDO> creditInfoSDOS = creditQueryRepository.batchQueryCreditList(creditQueryRequestList);
                if (CollectionUtils.isNotEmpty(creditInfoSDOS)){
                    list.addAll(creditInfoSDOS);
                }
            } catch (Throwable e) {
                log.error("分片查询信贷余额失败!", e);
            }

        }

        return Result.success(list);
    }

    /**
     * 查询分子公司对集团信贷列表
     * @param queryCompanyToGroupCreditListRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<List<CompanyToGroupCreditResponse>> queryCompanyToGroupCreditList(QueryCompanyToGroupCreditListRequest queryCompanyToGroupCreditListRequest) {
        //判断当前登录人权限
        EmployeeGetCurrentLoginResponse currentLoginResponse = bcOrderService.employeeGetCurrentLogin();
        if (currentLoginResponse == null || org.apache.commons.lang3.StringUtils.isBlank(currentLoginResponse.getRelatedOrganizationId())
                || org.apache.commons.lang3.StringUtils.isBlank(currentLoginResponse.getRelatedOrganizationType())){
            log.error("queryCompanyToGroupCreditList_no_auth");
            return Result.success(Lists.newArrayList());
        }
        Integer relatedOrganizationType = Integer.parseInt(currentLoginResponse.getRelatedOrganizationType());
        String relatedOrganizationId = currentLoginResponse.getRelatedOrganizationId();
        //层级在大区及大区之上的, 能看所有分子公司, 分子公司及分子公司之下的看当前分子公司的
        if (OrganizationTypeEnum.COMPANY.getCode().equals(relatedOrganizationType)){
            queryCompanyToGroupCreditListRequest.setCompanyId(relatedOrganizationId);
         }else if (OrganizationTypeEnum.COMPANY.getCode() < relatedOrganizationType){
            TopOrganizationListResponse topOrganizationListResponse = queryTopCompany(relatedOrganizationId);
            if (topOrganizationListResponse == null){
                return Result.success(Lists.newArrayList());
            }
            queryCompanyToGroupCreditListRequest.setCompanyId(topOrganizationListResponse.getId());
        }
        //分子公司之上不限制
        return creditQueryRepository.queryCompanyToGroupCreditList(queryCompanyToGroupCreditListRequest);
    }

    /**
     * 分子公司同步查询集团信贷
     * @param
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<CreditCallbackRequest> syncQueryCredit(BatchSyncQueryCreditRequest batchSyncQueryCreditRequest) {
        checkParams(batchSyncQueryCreditRequest);
        RestSapQueryCreditForCompanyToGroupSyncRequest request = new RestSapQueryCreditForCompanyToGroupSyncRequest();
        List<MnSapIf020SDO> sdoList = Lists.newArrayList();
        //批量查询
        batchSyncQueryCreditRequest.getRequests().forEach(syncQueryCreditRequest -> {
            MnSapIf020SDO sdo = new MnSapIf020SDO();
            sdo.setSaleOrganizationCode(syncQueryCreditRequest.getSaleOrganizationCode());
            sdo.setSapChannel(syncQueryCreditRequest.getSapChannel());
            sdo.setProductGroupCode(syncQueryCreditRequest.getProductGroupCode());
            sdo.setSoldPartCode(syncQueryCreditRequest.getSoldPartCode());
            sdoList.add(sdo);
        });
        request.setData(sdoList);
        try {
            Result<MnSap020Response> mnSap020ResponseResult = crPriceCenterService.restSapQueryCreditForCompanyToGroupSync(request);
            //请求返回数据转换成回调入参
            CreditCallbackRequest callbackRequest = convert2CreditCallbackRequest(mnSap020ResponseResult);
            return Result.success(callbackRequest);
        }catch (Throwable e){
            log.error("asyncQueryCredit_error",e);
            throw new FacadeException("OTS-07-008-01-16-028");
        }
    }

    private CreditCallbackRequest convert2CreditCallbackRequest(Result<MnSap020Response> result){
        CreditCallbackRequest callbackRequest = new CreditCallbackRequest();
//        callbackRequest.setMessageHeader(Optional.ofNullable(result).map(Result::getResult).map(MnSap020Response::getMessageHeader).orElse(null));
        if (result != null && result.getResult() != null){
            MnSap020Response response = result.getResult();
            callbackRequest.setMessageHeader(response.getMessageHeader());
            if (CollectionUtils.isNotEmpty(response.getData())){
                List<MnSap020CallbackSDO> sdoList = Lists.newArrayList();
                callbackRequest.setData(sdoList);
                response.getData().forEach(mnSap020SDO -> {
                    MnSap020CallbackSDO sdo = new MnSap020CallbackSDO();
                    sdo.setSapChannel(mnSap020SDO.getVTWEG());
                    sdo.setSaleOrganizationCode(mnSap020SDO.getVKORG());
                    sdo.setProductGroupCode(mnSap020SDO.getSPART());
                    sdo.setSoldPartCode(mnSap020SDO.getKUNNR());
                    sdo.setCreditLimit(mnSap020SDO.getKLIMK());
                    sdo.setReceivableBalance(mnSap020SDO.getSKFOR());
                    sdo.setTransitAmount(mnSap020SDO.getSSOBL());
                    sdo.setUnShipAmount(mnSap020SDO.getSAUFT());
                    sdo.setTotalCreditBalance(mnSap020SDO.getOBLIG());
                    sdo.setCreditBalance(mnSap020SDO.getDMBTR());
                    sdo.setExt(mnSap020SDO.getEXT());
                    sdo.setExt1(mnSap020SDO.getEXT1());
                    sdoList.add(sdo);
                });
            }
        }
        return callbackRequest;
    }

    /**
     * 刷新 (重新请求) 分子公司对集团的信贷查询
     * @param request
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> refreshSyncQueryCredit(RefreshSyncQueryCreditRequest request) {
        checkParams(request);
        //校验下当前登录人是否有权限
        checkPermission(request.getSoldPartCode());
        //查询缓存 定时任务请求信贷时,设置缓存, 限制页面刷新请求sap信贷
//        checkAndSetCache(request.getSoldPartCode());

        SyncQueryCreditRequest syncQueryCreditRequest = new SyncQueryCreditRequest();
        BeanUtils.copyProperties(request,syncQueryCreditRequest);
        BatchSyncQueryCreditRequest batchSyncQueryCreditRequest = new BatchSyncQueryCreditRequest();
        batchSyncQueryCreditRequest.setRequests(Lists.newArrayList(syncQueryCreditRequest));
        Result<CreditCallbackRequest> result = syncQueryCredit(batchSyncQueryCreditRequest);
        if (result == null || !result.isSuccess()){
            throw new FacadeException("OTS-07-008-01-16-028");
        }
        Result<Boolean> callback = creditWriteService.callback(result.getResult());

        return callback;
    }

    /**
     * 定时任务批量异步查询分子公司对集团的信贷
     * @return
     */
    @Override
    @FacadeInvoker(value = "批量执行异步查询信贷")
    public Result<Boolean> batchSyncQueryCredit() {

        StopWatch watch = new StopWatch();
        watch.start("batchAsyncQueryCredit");
        //获取6000组织
        BaselineGetOrganizationByCodes2Request byCodes2Request = new BaselineGetOrganizationByCodes2Request();
        byCodes2Request.setIds(Lists.newArrayList(SALE_ORGANIZATION_CODE));
        BaselineGetOrganizationByCodes2Response response = baseDataService.baselineGetOrganizationByCodes2(byCodes2Request);
        if (response == null || CollectionUtils.isEmpty(response.getResult())){
            return Result.success(null);
        }
        //获取6000组织下的分子公司
        String id = response.getResult().get(0).getId();
        GetDownOrganizationListRequest request = new GetDownOrganizationListRequest();
        request.setType(OrganizationTypeEnum.COMPANY.getCode());
        request.setId(id);
        Result<List<OrganizationSDO>> downOrganizationList = crPlatformEnhanceService.getDownOrganizationList(request);
        //批量请求sap信贷
        if (downOrganizationList != null && CollectionUtils.isNotEmpty(downOrganizationList.getResult())){
            Set<String> soldPartCodes = Sets.newHashSet();
            long delayTime = Optional.ofNullable(CrPriceCenterConstants.SYNC_QUERY_CREDIT_DELAY_TIME()).orElse(3000L);
            //分组条数,分批次请求
            Long partition =Optional.ofNullable(CrPriceCenterConstants.SYNC_QUERY_CREDIT_PARTITION_NUM()).orElse(50L);
            //47家分子公司 分批请求 也可以47家同时请求
            downOrganizationList.getResult().removeIf(organizationSDO -> !targetSoldPartCodesSet.contains(organizationSDO.getCode()));
            List<List<OrganizationSDO>> partList = Lists.partition(downOrganizationList.getResult(), partition.intValue());
            for (List<OrganizationSDO> organizationSDOS : partList) {
                BatchSyncQueryCreditRequest batchSyncQueryCreditRequest = new BatchSyncQueryCreditRequest();
                List<SyncQueryCreditRequest> syncQueryCreditRequests = Lists.newArrayList();
                batchSyncQueryCreditRequest.setRequests(syncQueryCreditRequests);
                //构造信贷请求
                organizationSDOS.forEach(organizationSDO -> {
                    //循环分子公司列表 异步查询分子公司对集团的信贷
                    SyncQueryCreditRequest syncQueryCreditRequest = new SyncQueryCreditRequest();
                    syncQueryCreditRequest.setSaleOrganizationCode(SALE_ORGANIZATION_CODE);
                    syncQueryCreditRequest.setSapChannel(SAP_CHANNEL);
                    syncQueryCreditRequest.setProductGroupCode(PRODUCT_GROUP_CODE);
                    syncQueryCreditRequest.setSoldPartCode(organizationSDO.getCode());
                    syncQueryCreditRequests.add(syncQueryCreditRequest);
                });
                try {
                    //同步请求分子公司对集团的信贷
                    Result<CreditCallbackRequest> syncQueryResult = syncQueryCredit(batchSyncQueryCreditRequest);
                    if (!syncQueryResult.isSuccess() || StringUtils.isNotBlank(syncQueryResult.getMessage())){
                        throw new FacadeException(syncQueryResult.getErrorCode(),syncQueryResult.getMessage());
                    }
                    //接收请求结果
                    Result<Boolean> callback = creditWriteService.callback(syncQueryResult.getResult());
                    if (callback == null || !callback.isSuccess()){
                        throw new FacadeException("OTS-07-008-01-16-030");
                    }
                } catch (Throwable e) {
                    organizationSDOS.stream().map(OrganizationSDO::getCode).forEach(soldPartCodes::add);
                    log.error("batchAsyncQueryCredit_error",e);
                }
            }
            //返回查询失败的售达方编码
            if (CollectionUtils.isNotEmpty(soldPartCodes)){
                log.error("batchAsyncQueryCredit_fail_soldPartCodes:{}", JSON.toJSONString(soldPartCodes));
                watch.stop();
                log.info("batchAsyncQueryCredit_watch:{}",JSON.toJSONString(watch));
                Result result = new Result();
                result.setSuccess(false);
                result.setMessage(soldPartCodes.stream().collect(Collectors.joining(",")));
                return result;
            }
        }
        watch.stop();
        log.info("batchAsyncQueryCredit_watch:{}",JSON.toJSONString(watch));

        return Result.success(true);
    }

    //查询参数校验
    private void checkParams(BatchSyncQueryCreditRequest request){
        if (request == null || CollectionUtils.isEmpty(request.getRequests())){
            throw new FacadeException("OTS-07-008-01-16-031");
        }
        request.getRequests().forEach(syncQueryCreditRequest -> {
            if (!SALE_ORGANIZATION_CODE.equals(syncQueryCreditRequest.getSaleOrganizationCode())){
                throw new FacadeException("OTS-07-008-01-16-011");
            }
            if (!SAP_CHANNEL.equals(syncQueryCreditRequest.getSapChannel())){
                throw new FacadeException("OTS-07-008-01-16-012");
            }
            if (!PRODUCT_GROUP_CODE.equals(syncQueryCreditRequest.getProductGroupCode())){
                throw new FacadeException("OTS-07-008-01-16-013");
            }
            if (StringUtils.isBlank(syncQueryCreditRequest.getSoldPartCode())){
                throw new FacadeException("OTS-07-008-01-16-004");
            }
        });

    }

    //检查并设置缓存
    private void checkAndSetCache(String soldPartCode){
        String cache = epochCacheService.get(BcOrderConstants.REDIS_CACHE_CODE(), REFRESH_CREDIT_QUERY_KEY + soldPartCode);
        if (StringUtils.isNotBlank(cache)){
            throw new FacadeException("OTS-07-008-01-16-029");
        }
        Long expire = Optional.ofNullable(CrPriceCenterConstants.REFRESH_SYNC_QUERY_CREDIT_LIMIT_TIME()).orElse(REFRESH_TIME_EXPIRE);
        epochCacheService.put(BcOrderConstants.REDIS_CACHE_CODE(),REFRESH_CREDIT_QUERY_KEY + soldPartCode,
                soldPartCode,expire, TimeUnit.SECONDS);
    }

    //获取渠道/部门的上级销售组织
    private TopOrganizationListResponse queryTopCompany(String organizationId){
        if (org.apache.commons.lang3.StringUtils.isBlank(organizationId)){
            return null;
        }
        GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
        getTopOrganizationListRequest.setId(organizationId);
        getTopOrganizationListRequest.setType(OrganizationTypeEnum.COMPANY.getCode());
        Result<List<TopOrganizationListResponse>> topOrganizationList = crPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
        if (topOrganizationList != null && CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
            return topOrganizationList.getResult().stream().filter(topOrganizationListResponse -> OrganizationTypeEnum.COMPANY.getCode().equals(topOrganizationListResponse.getType()))
                    .findFirst().orElse(null);
        }
        return null;
    }

    //校验当前登录人权限
    private void checkPermission(String soldPartCode){
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        if (loginEmployeeInfo == null || loginEmployeeInfo.getOrganizationSDO() == null ||
                StringUtils.isBlank(loginEmployeeInfo.getOrganizationSDO().getId()) ||
                loginEmployeeInfo.getOrganizationSDO().getType() == null
        ){
            throw new FacadeException("OTS-01-005-02-15-033");
        }
        String id = loginEmployeeInfo.getOrganizationSDO().getId();
        Integer type = loginEmployeeInfo.getOrganizationSDO().getType();
        String code = loginEmployeeInfo.getOrganizationSDO().getCode();

        //层级在大区及大区之上的, 能看所有分子公司, 分子公司及分子公司之下的看当前分子公司的
        if (OrganizationTypeEnum.COMPANY.getCode().equals(type)){
            if (!code.equals(soldPartCode)){
                throw new FacadeException("OTS-01-005-02-15-033");
            }
        }else if (OrganizationTypeEnum.COMPANY.getCode() < type){
            TopOrganizationListResponse topOrganizationListResponse = queryTopCompany(id);
            if (topOrganizationListResponse == null || !Objects.equals(topOrganizationListResponse.getCode(),
                    soldPartCode)){
                throw new FacadeException("OTS-01-005-02-15-033");
            }
        }
    }

    private void checkParams(RefreshSyncQueryCreditRequest request){
        if (StringUtils.isBlank(request.getSoldPartCode())){
            throw new FacadeException("OTS-07-008-01-16-004");
        }
        if (StringUtils.isNotBlank(request.getSaleOrganizationCode())){
            request.setSaleOrganizationCode(request.getSaleOrganizationCode().trim());
        }
        if (!SALE_ORGANIZATION_CODE.equals(request.getSaleOrganizationCode())){
            throw new FacadeException("OTS-07-008-01-16-011");
        }
        if (StringUtils.isNotBlank(request.getSapChannel())){
            request.setSapChannel(request.getSapChannel().trim());
        }
        if (!SAP_CHANNEL.equals(request.getSapChannel())){
            throw new FacadeException("OTS-07-008-01-16-012");
        }
        if (StringUtils.isNotBlank(request.getProductGroupCode())){
            request.setProductGroupCode(request.getProductGroupCode().trim());
        }
        if (!PRODUCT_GROUP_CODE.equals(request.getProductGroupCode())){
            throw new FacadeException("OTS-07-008-01-16-013");
        }
        if (StringUtils.isBlank(request.getSoldPartCode())){
            throw new FacadeException("OTS-07-008-01-16-004");
        }
        if (request.getSoldPartCode().length() > MAX_LENGTH){
            throw new FacadeException("OTS-07-008-01-16-033");
        }
        request.setSoldPartCode(request.getSoldPartCode().trim());
        if (!NumberUtil.isInteger(request.getSoldPartCode())){
            throw new FacadeException("OTS-07-008-01-16-026",request.getSoldPartCode());
        }
        if (!targetSoldPartCodesSet.contains(request.getSoldPartCode())){
            throw new FacadeException("OTS-07-008-01-16-034");
        }
    }
}
